<?php
/**
 * Created by PhpStorm.
 * User: function
 * Date: 2018-05-02
 * Time: 10:18
 */

namespace app\admin\controller;
use app\common\controller\Admin;
use app\common\logic\AdPlaceLogic;
use app\common\model\Ad;
class AdPlace extends Admin
{
    public function index()
    {
        
        $logic = new AdPlaceLogic();
        $params = paramForm();
        
        if (\think\Request::instance()->isAjax()) {
            $params['paginate'] = true;
            $logic->setValue('order','id desc');
            
            if (isset($params['title'])){
                $params['title'] = array('like','%'.$params['title'].'%');
            }

            $lists = $logic->getList($params);
            foreach ($lists as $place){
                $place['adCount'] = Ad::where('pid',$place->id)->count();
            }
            success($lists);
        } else {
            return $this->fetch();
        }
        
    }
    
    public function save(){
        
        $rule = [
            'title|标题'=>'require',
            'price|单价'=>'require',
            'height|高度'=>'require',
            'width|宽度'=>'require',
        ];
        $params = paramForm();
        $this->validate($params,$rule);
        
        $file = request()->file('thumb');
        if($file){
            $params['thumb']=$this->uploadToAlyun($file);
        }else{
            $this->error('示意图必传');
        }
        
        $logic = new AdPlaceLogic();
        $id = $logic->add($params);
        
        if(!$id)$this->error('新增失败');
        $this->success('新增成功','index');
        
    }
    
    
    public function edit($id){
        $logic = new AdPlaceLogic();
        $place = $logic->findModel($id);
        $this->assign('model',$place);
        return $this->fetch();
    }
    
    public function update($id){
        $logic = new AdPlaceLogic();
        $place = $logic->findModel($id);
    
        $params = paramForm();
        $file = request()->file('thumb');
        if($file){
            $params['thumb']=$this->uploadToAlyun($file);
        }
    
        $rt = $place->allowField(true)->save($params,['id'=>$id]);
        if ($rt) {
            $this->success("更新成功！", "index");
        } else {
            $this->error("更新失败!");
        }
        
       
    }
    
    
}